//
//  WaveformView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/10.
//

import UIKit

class WaveformView: UIView {
    
    // MARK: - Constants
    private static let MAX_BARS = 8 // 最大条形数量，与Android保持一致
    private static let BASE_COLOR = UIColor(red: 31/255.0, green: 125/255.0, blue: 251/255.0, alpha: 1.0) // 与Android相同的蓝色
    
    // MARK: - Properties
    private var amplitude: CGFloat = 0.0
    private var smoothAmplitude: CGFloat = 0.0
    private var barHeights: [CGFloat] = Array(repeating: 0.0, count: MAX_BARS)
    private var lastUpdateTime: TimeInterval = 0
    
    // MARK: - Public Methods
    func updateAmplitude(_ amplitude: CGFloat) {
        
        self.amplitude = amplitude
        // 平滑处理，与Android逻辑一致
        smoothAmplitude = smoothAmplitude * 0.7 + amplitude * 0.3
        shiftBars()
        setNeedsDisplay()
        
    }
    
    // MARK: - Private Methods
    private func shiftBars() {
        // 将旧数据向左移动
        for i in 0..<(WaveformView.MAX_BARS - 1) {
            barHeights[i] = barHeights[i + 1]
        }
        
        // 生成新数据（带动态效果，与Android逻辑一致）
        let currentTime = Date().timeIntervalSince1970 * 1000 // 毫秒
        let waveFactor = sin(currentTime * 0.005)
        let dynamicAmplitude = smoothAmplitude * (0.9 + 0.1 * waveFactor)
        
        barHeights[WaveformView.MAX_BARS - 1] = dynamicAmplitude
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        let width = rect.width
        let height = rect.height
        
        
        // 计算条形参数（与Android逻辑一致）
        let barWidth = width / CGFloat(WaveformView.MAX_BARS + 2)
        let spacing = barWidth / 4
        
        // 设置填充颜色
        context.setFillColor(WaveformView.BASE_COLOR.cgColor)
        
        // 绘制条形
        for i in 0..<WaveformView.MAX_BARS {
            let barHeight = barHeights[i] * height * 0.8 // 与Android一致，使用80%的高度
            let left = spacing + CGFloat(i) * (barWidth + spacing)
            let top = height - barHeight
            let right = left + barWidth
            let bottom = height
            
            
            // 绘制圆角条形（与Android一致）
            let barRect = CGRect(x: left, y: top, width: barWidth, height: barHeight)
            let path = UIBezierPath(roundedRect: barRect, cornerRadius: barWidth / 2)
            context.addPath(path.cgPath)
            context.fillPath()
        }
    }
}
